package com.djt.book_system.controller;

import com.djt.book_system.entity.Users;
import com.djt.book_system.service.UsersService;
import com.djt.book_system.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Users)表控制层
 *
 * @author makejava
 * @since 2021-05-19 10:48:15
 */
@RestController
@RequestMapping("users")
public class UsersController {
    /**
     * 服务对象
     */
    @Resource
    private UsersService usersService;

    /**
     * 通过主键查询单条数据
     *
     * @param uid 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Users selectOne(Integer uid) {
        return this.usersService.queryById(uid);
    }

    /**
     * 条件查询或查询所有
     *
     * @param conditional Users对象，条件
     * @param page 页码
     * @param limit 每页数据数
     * @return User对象集合
     */
    @GetMapping("select")
    public Result select(Users conditional,int page , int limit) {
        try {
            if (conditional.getUsex().equals("男")){
                conditional.setUsex("1");
            }else if (conditional.getUsex().equals("女")){
                conditional.setUsex("0");
            }
        }catch (Exception e){

        }
        int offset = (page-1)*limit;
        List<Users> users = usersService.conditionalQuery(conditional,offset,limit);
        int count = usersService.usersCount(conditional);
        if (users.size()==0){
            try {
                offset = (page-1-1)*limit;
                users = usersService.conditionalQuery(conditional,offset,limit);
                return Result.success(count,users);
            }catch (Exception e){

                return Result.success(0,null);
            }
        }
        return Result.success(count,users);
    }
    /**
     * 添加一条数据
     *
     * @param users 用户对象
     */
    @PostMapping("addOne")
    public void addOne(Users users){
        usersService.insert(users);
    }

    /**
     * 修改单个用户数据
     *
     * @param users 用户对象
     */
    @PostMapping("updateOne")
    public void updateOne(Users users){

        usersService.update(users);
    }

    /**
     * 根据主键删记录
     *
     * @param uid 主键
     */
    @GetMapping("deleteOne")
    public void deleteOne(Integer uid){
        usersService.deleteById(uid);
    }

    /**
     * 批量删除记录
     *
     * @param uids uid数组
     */
    @GetMapping("batchRemove")
    public void batchRemove(int[] uids){
        usersService.batchRemove(uids);
    }

}
